package com.zys.el.time.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zys.el.time.entity.AbsorbedDeal;
import com.zys.el.time.entity.Deal;
import com.zys.el.time.mapper.AbsorbedDealMapper;
import com.zys.el.time.service.IAbsorbedDealService;
import com.zys.el.time.utils.TimeUtil;
import com.zys.el.time.vojo.AbsorbedAnalysis;
import com.zys.el.time.vojo.AbsorbedDetail;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Service
public class AbsorbedDealService extends ServiceImpl<AbsorbedDealMapper, AbsorbedDeal>
        implements IAbsorbedDealService {

    @Override
    public AbsorbedAnalysis getDealAnalysis(LocalDate firstDate, LocalDate lastDate, Long userId) {
        List<Deal> dealList = this.getBaseMapper().getListByAbDealRightJoinDeal(userId, firstDate, lastDate);

        log.debug(dealList.toString());

        HashMap<Long, AbsorbedDetail> map = new HashMap<>();
        String allAbsorbedDuration = "0:0:0";
        for (Deal deal : dealList) { // 归类，计算每个待办时长总和
            Long dealId = deal.getDealId();
            AbsorbedDetail d = null;
            if (map.containsKey(dealId)) { // 更新值
                d = map.get(dealId);
                String hourMin = TimeUtil.handleTimeBackHourMinSec(deal.getAbsorbedDuration(), d.getAllMinutes());
                d.setAllMinutes(hourMin);
                d.setTimes(d.getTimes() + 1);
            }
            if (d == null) { // 赋值
                d = new AbsorbedDetail();
                d.setDealId(deal.getDealId());
                d.setTimes(1);
                d.setAllMinutes(deal.getAbsorbedDuration());
                d.setUserId(deal.getUserId());
                d.setName(deal.getTitle());
            }
            // 计算总专注时长
            allAbsorbedDuration = TimeUtil.handleTimeBackHourMinSec(allAbsorbedDuration, deal.getAbsorbedDuration());
            map.put(dealId, d);
        }

        log.debug(map.toString());
        return new AbsorbedAnalysis(userId, allAbsorbedDuration, (long) dealList.size(), new ArrayList<>(map.values()));
    }

    @Override
    public List<AbsorbedDeal> getAbDealByDealId(String dealId) {
        return this.getBaseMapper().getAbDealByDealId(dealId);
    }

    @Override
    public List<AbsorbedDeal> getAbDealByUserId(String userId) {
        return this.getBaseMapper().getAbDealByUserId(userId);
    }
}




